﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Text;
using Common;

public partial class shopping_orderutility : MemberPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;
        PageBegin();

        switch (RequestBase.GetFormString("otype"))
        {
            case "getregionlist":
                LoadingRegionList();
                break;
            case "getaddressobj":
                InitializeAddressObj();
                break;
            case "getaddresslist":
                LoadShipAddressList();
                break;
            case "addshippingaddress":
                SaveShipAddressInfo();
                break;
            case "modifyshippingaddress":
                SaveShipAddressInfo();
                break;
            case "loadingorderitems":
                LoadingOrderItems();
                break;
            case "loadingorderilist":
                LoadingOrderList();
                break;
            case "loadingorderilistforindex":
                LoadingOrderListForIndex();
                break;
            case "updateorderitemqty":
                UpdateOrderQty();
                break;
            case "removeorderitem":
                RemoveOrderItem();
                break;
            case "totalorderamount":
                TotalOrderAmount();
                break;
        }
    }

    #region 获取三级地区级联目录数据
    /// <summary>
    /// 获取三级地区级联目录数据
    /// </summary>
    void LoadingRegionList()
    {
        string parentid = RequestBase.GetFormString("parentid");
        StringBuilder selOptions = new StringBuilder();
        string items = "<option value=\"{0}\">{1}</option>";

        string layer = RequestBase.GetFormString("layer");
        switch (layer)
        {
            case "1":
                selOptions.Append(string.Format(items, "", "-- 请选择省份 --"));
                break;
            case "2":
                selOptions.Append(string.Format(items, "", "-- 请选择城市 --"));
                break;
            case "3":
                selOptions.Append(string.Format(items, "", "-- 请选择区县 --"));
                break;
        }

        DataTable dat = BLL.CommonBLL.Select(
            "RegionBase",
            "RegionName, RegionId",
            " AND DeletionStateCode = 0 AND ParentId = " + parentid + " AND Layer=" + layer + " ORDER BY RegionName ASC");

        foreach (DataRow dr in dat.Select(""))
        {
            selOptions.Append(string.Format(items, dr["RegionId"].ToString(), dr["RegionName"].ToString()));
        }

        dat.Clear();
        dat.Dispose();
        BLL.AjaxHelper.ResponseWrite(selOptions.ToString());
    }
    #endregion

    #region 送货地址处理方法
    /// <summary>
    /// 送货地址簿
    /// </summary>
    Model.ShippingAddressBase AddressObj
    {
        get
        {
            Model.ShippingAddressBase _addressObj = new Model.ShippingAddressBase();

            if (!string.IsNullOrEmpty(RequestBase.GetFormString("txtShippingAddressId")))
                _addressObj.ShippingAddressId = RequestBase.GetFormString("txtShippingAddressId");

            _addressObj.ShipAddressName = RequestBase.GetFormString("txtShipAddressName");
            _addressObj.ShipAddress = RequestBase.GetFormString("txtShipAddress");
            _addressObj.ShipCounties = RequestBase.GetFormString("txtShipCounties");
            _addressObj.ShipCity = RequestBase.GetFormString("txtShipCity");
            _addressObj.ShipState = RequestBase.GetFormString("txtShipState");
            _addressObj.ShipCountry = "中国";
            _addressObj.ShipZip = RequestBase.GetFormString("txtShipZip");
            _addressObj.ShipTel = RequestBase.GetFormString("txtShipTel");
            _addressObj.ShipMobile = RequestBase.GetFormString("txtShipMobile");
            _addressObj.ShipToName = RequestBase.GetFormString("txtShipToName");
            _addressObj.ShipCountiesId = int.Parse((RequestBase.GetFormString("txtShipCountiesId") == "") ? "0" : RequestBase.GetFormString("txtShipCountiesId"));
            _addressObj.ShipCityId = int.Parse((RequestBase.GetFormString("txtShipCityId") == "") ? "0" : RequestBase.GetFormString("txtShipCityId"));
            _addressObj.ShipStateId = int.Parse((RequestBase.GetFormString("txtShipStateId") == "") ? "0" : RequestBase.GetFormString("txtShipStateId"));
            _addressObj.ShipCountryId = 0;
            _addressObj.UserId = this.UserId;
            _addressObj.StatusCode = 0;

            return _addressObj;
        }
    }
    /// <summary>
    /// 获取送货地址信息
    /// </summary>
    void InitializeAddressObj()
    {
        Model.ShippingAddressBase _obj = BLL.ShippingAddressBase.GetObjectById(RequestBase.GetFormString("txtShippingAddressId"));
        StringBuilder GetValues = new StringBuilder();
        GetValues.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?><ShippingAddressBase><fileds>");
        GetValues.Append("<filed name=\"ShipAddressName\">" + _obj.ShipAddressName + "</filed>");
        GetValues.Append("<filed name=\"ShipAddress\">" + _obj.ShipAddress + "</filed>");
        GetValues.Append("<filed name=\"ShipCounties\">" + _obj.ShipState + " | " + _obj.ShipCity + " | " + _obj.ShipCounties + "</filed>");
        GetValues.Append("<filed name=\"ShipZip\">" + _obj.ShipZip + "</filed>");
        GetValues.Append("<filed name=\"ShipTel\">" + _obj.ShipTel + "</filed>");
        GetValues.Append("<filed name=\"ShipMobile\">" + _obj.ShipMobile + "</filed>");
        GetValues.Append("<filed name=\"ShipToName\">" + _obj.ShipToName + "</filed>");
        GetValues.Append("<filed name=\"CountieId\">" + _obj.ShipCountiesId.ToString() + "</filed>");
        GetValues.Append("<filed name=\"CityId\">" + _obj.ShipCityId.ToString() + "</filed>");
        GetValues.Append("<filed name=\"ProvinceId\">" + _obj.ShipStateId.ToString() + "</filed>");
        GetValues.Append("<filed name=\"ShipCountryId\">" + _obj.ShipCountryId.ToString() + "</filed>");
        GetValues.Append("</fileds></ShippingAddressBase>");

        BLL.AjaxHelper.ResponseWriteXML(GetValues.ToString());
    }
    /// <summary>
    /// 获取用户地址列表
    /// </summary>
    void LoadShipAddressList()
    {
        StringBuilder selOptions = new StringBuilder();
        string items = "<option value=\"{0}\">{1}</option>";

        DataTable dat = BLL.CommonBLL.Select("ShippingAddressBase", "*", " AND UserId = '" + this.UserId + "' ORDER BY ShipAddressName ASC");

        foreach (DataRow dr in dat.Select(""))
        {
            selOptions.Append(string.Format(items, dr["ShippingAddressId"].ToString(), dr["ShipAddressName"].ToString()));
        }

        dat.Dispose();
        BLL.AjaxHelper.ResponseWrite(selOptions.ToString());
    }
    /// <summary>
    /// 保存送货地址
    /// </summary>
    void SaveShipAddressInfo()
    {
        string result = "";
        if (RequestBase.GetFormString("otype") == "addshippingaddress")
        {
            result = BLL.ShippingAddressBase.CreateShippingAddress(AddressObj);
        }

        if (RequestBase.GetFormString("otype") == "modifyshippingaddress")
        {
            result = BLL.ShippingAddressBase.ModifyShippingAddress(AddressObj);
        }

        switch (result.Split('|')[0])
        {
            case "succeeded":
                BLL.AjaxHelper.ResponseWrite(result);
                break;
            default:
                BLL.AjaxHelper.ResponseWrite(result);
                break;
        }
    }
    #endregion

    #region 订单商品明细修改
    void LoadingOrderItems()
    {
        try
        {
            string ctrl = "~/_controls/ctlCartItems.ascx";
            Control uc_rep = LoadControl(ctrl);
            Repeater rptOrderItems = (Repeater)uc_rep.FindControl("rptOrderItems");

            DataTable dat = BLL.CommonBLL.Select("vw_Profiles_Items", "*", " AND Username = '" + this.User.Identity.Name + "' AND ProfileName = 'OrderItems' AND OrderId = '" + RequestBase.GetFormString("orderid") + "' ORDER BY ProductNumber ASC");
            rptOrderItems.DataSource = dat;
            rptOrderItems.DataBind();

            StringBuilder strb = new StringBuilder();
            StringWriter sw = new StringWriter(strb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            rptOrderItems.RenderControl(htw);

            BLL.AjaxHelper.ResponseWrite(strb.ToString());
        }
        catch (System.Threading.ThreadAbortException err)
        {
            //nothing   to   do   
        }
        catch (Exception err)
        {
            BLL.AjaxHelper.ResponseWrite(err.Message);
        }
    }
    void UpdateOrderQty()
    {
        if (Utils.IsNumber(RequestBase.GetFormString("qty")))
        {
            Profile.OrderItems.SetQuantity(RequestBase.GetFormString("_itemid"), int.Parse(RequestBase.GetFormString("qty")));
            Profile.Save();

            BLL.AjaxHelper.ResponseWrite("succeeded");
        }
        else
        {
            BLL.AjaxHelper.ResponseWrite("请输入数值型数据！");
        }
    }
    void RemoveOrderItem()
    {
        Profile.OrderItems.Remove(RequestBase.GetFormString("_itemid"));
        Profile.Save();

        BLL.AjaxHelper.ResponseWrite("succeeded");
    }
    void TotalOrderAmount()
    {
        string orderid = RequestBase.GetFormString("orderid");

        decimal total = 0;
        foreach (Model.CardItems _item in Profile.OrderItems.CartItems)
        {
            if (_item.OrderId == orderid)
                total += _item.Price * _item.Quantity;
        }

        BLL.AjaxHelper.ResponseWrite(total.ToString());
    }
    #endregion

    #region 订单管理
    void LoadingOrderList()
    {
        try
        {
            string ctrl = "~/_controls/ctlCartItems.ascx";
            Control uc_rep = LoadControl(ctrl);
            Repeater rptOrderManageList = (Repeater)uc_rep.FindControl("rptOrderManageList");

            StringBuilder SQL = new StringBuilder();
            SQL.AppendFormat(" AND UserId = '{0}'", this.UserId);

            if (RequestBase.GetFormString("querytext") != "" && !FilterHandler.ExistBadWord(RequestBase.GetFormString("querytext")) && Utils.IsSafeSqlString(RequestBase.GetFormString("querytext")))
            {
                SQL.Append(" AND (OrderNumber LIKE '%" + RequestBase.GetFormString("querytext") + "%')");
            }
            if (RequestBase.GetFormString("status") != "")
            {
                SQL.AppendFormat(" AND StatusCode = {0}", RequestBase.GetFormString("status"));
            }

            DBUtility.Pagination pagination = new DBUtility.Pagination();
            /// 页码
            if (RequestBase.GetFormString("page") != "" && Utils.IsNumber(RequestBase.GetFormString("page")))
                pagination.Sequence = Convert.ToInt32(RequestBase.GetFormString("page"));
            else
                pagination.Sequence = 1;

            if (RequestBase.GetFormString("upcount") != "" && Utils.IsNumber(RequestBase.GetFormString("upcount")))
                pagination.PageUpCount = Convert.ToInt32(RequestBase.GetFormString("upcount"));

            if (RequestBase.GetFormString("direction") == "next")
                pagination.Direction = "next";
            else
                pagination.Direction = "prev";

            pagination.PageBarCount = 8;
            pagination.PageSize = 12;
            pagination.Primarykey = "OrderId";
            pagination.SearchField = "*";
            pagination.TableName = "OrderBase";
            pagination.ItemUnit = "条记录";
            pagination.SearchSentence = SQL.ToString();
            pagination.SortSentence = " ORDER BY OrderDate DESC";

            rptOrderManageList.DataSource = pagination.GetDataTable();
            rptOrderManageList.DataBind();

            pagination.GoNumeberPageBarCn3Asyn();
            uc_rep.GetType().GetProperty("PaginationBar").SetValue(uc_rep, pagination.PageBar, null);

            StringBuilder strb = new StringBuilder();
            StringWriter sw = new StringWriter(strb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            rptOrderManageList.RenderControl(htw);

            BLL.AjaxHelper.ResponseWrite(strb.ToString());
        }
        catch (System.Threading.ThreadAbortException err)
        {
            //nothing   to   do   
        }
        catch (Exception err)
        {
            BLL.AjaxHelper.ResponseWrite(err.Message);
        }
    }

    void LoadingOrderListForIndex()
    {
        try
        {
            StringBuilder SQL = new StringBuilder();
            SQL.AppendFormat(" AND UserId = '{0}'", this.UserId);

            string ctrl = "~/_controls/ctlCartItems.ascx";
            Control uc_rep = LoadControl(ctrl);
            Repeater rptOrderManageListForHome = (Repeater)uc_rep.FindControl("rptOrderManageListForHome");

            DataTable dat = BLL.CommonBLL.Select("OrderBase", "TOP 6 *", SQL + " ORDER BY OrderDate DESC");
            rptOrderManageListForHome.DataSource = dat;
            rptOrderManageListForHome.DataBind();

            StringBuilder strb = new StringBuilder();
            StringWriter sw = new StringWriter(strb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            rptOrderManageListForHome.RenderControl(htw);

            BLL.AjaxHelper.ResponseWrite(strb.ToString());
        }
        catch (System.Threading.ThreadAbortException err)
        {
            //nothing   to   do   
        }
        catch (Exception err)
        {
            BLL.AjaxHelper.ResponseWrite(err.Message);
        }
    }
    #endregion
}